import React, { useState, useEffect } from 'react';
import { Cascader } from 'antd';
import 'antd/dist/reset.css';
import { useQuery } from "react-query"
import axios from "axios"
import mock from "@/mock/index"

// 根据环境变量，开发环境下开启
if (process.env.NODE_ENV === 'development') {
  mock()
}

// 这个假数据，替换成你的请求就好了
/* var _data = [
  {
    "code": "11",
    "parentCode": "0",
    "deep": 0,
    "extName": "北京市",
    // isLeaf 应该根据 deep 来给true 还是false 
    isLeaf: false
  }] */


interface Option {
  code: string;
  extName: string;
  parentCode?: String,
  deep?: Number,
  children?: Option[];
  isLeaf?: boolean;
  loading?: boolean;
}
// 格式化函数
function resetData(data: any) {
  return data.map((item: any) => {
    item.isLeaf = item.deep ? true : false
    return item
  })
}

const App: React.FC = () => {
  const optionLists: Option[] = []
  const [options, setOptions] = useState<Option[]>(optionLists);

  // 页面打开后立即要请求省的数据
  let { isLoading } = useQuery('getCity', () => axios.post('/antd/city').then((res: any) => {
    setOptions(resetData(res.data))
    return res.data
  }))

  if (isLoading) {
    return <div>正在加载……</div>
  }

  const onChange: any = (value: string[], selectedOptions: Option[]) => {
    console.log('这里是选择的值，用来给外部使用', value, selectedOptions);
  };

  const loadData: any = async (selectedOptions: Option[]) => {

    const targetOption: any = selectedOptions[selectedOptions.length - 1];
    // isLeaf === true
    if (targetOption.isLeaf) {
      return
    }
    targetOption.loading = true;
    // 请求的是展开的子级数据
    let { data } = await axios.post('/antd/city', { id: targetOption.id })
    // 等数据回来，赋值就好

    if (data) {
      targetOption.loading = false;
      targetOption.children = resetData(data)
      setOptions([...options]);
    } else if (data === false) {
      targetOption.loading = false;
      targetOption.isLeaf = true
    }
  };

  return <Cascader fieldNames={{ label: 'extName', value: 'code', children: 'children' }} options={options} loadData={loadData} onChange={onChange} changeOnSelect />;
};

export default App;